import { useEffect, useRef } from "react";
import { MessageItem } from "./message-item";
import { type MessageProps } from "@/store/useChatStore";
import { ScrollArea } from "@/components/ui/scroll-area";

export function MessageList({ messages }: { messages: MessageProps[] }) {
  const bottomRef = useRef<HTMLDivElement | null>(null);
  useEffect(() => {
    // 每次 messages 变化时滚到底
    bottomRef.current?.scrollIntoView({ behavior: "auto" });
  }, [messages]);

  return (
    <ScrollArea className=" max-h-[calc(100vh-160px)] w-full bg-muted/20">
      <div className=" h-full px-4 space-y-3">
        {messages.map((msg) => (
          <MessageItem
            key={msg.id}
            id={msg.id}
            role={msg.role}
            content={msg.content[0].content as string}
          />
        ))}
        <div ref={bottomRef} />
      </div>
    </ScrollArea>
  );
}
